package cn.waka.sys.admin.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import cn.waka.sys.admin.object.Page;
import cn.waka.sys.admin.object.Result;
import cn.waka.sys.admin.service.FaceService;
import cn.waka.sys.admin.service.RedisService;
import cn.waka.sys.admin.utils.Validator;

@RestController
@RequestMapping("/face")
public class FaceController extends BaseController{
	
	@Autowired
	private FaceService faceService;
	@Autowired
	private RedisService redisService;
	
	@RequestMapping(path = "/index", name="人脸识别包列表")
	public ModelAndView pageList(HttpServletRequest req, HttpServletResponse res){
		String pStr=req.getParameter("page");
		Page p=new Page();
		if(pStr!=null&&Validator.isNum(pStr)){
			p.setPage(Integer.parseInt(pStr));
		}
		String sizeStr=req.getParameter("size");
		if(sizeStr!=null&&Validator.isNum(sizeStr)){
			p.setSize(Integer.parseInt(sizeStr));
		}
		
		Map<String,String> param=new HashMap<String,String>();
		
		faceService.findPage(p,param);
		ModelAndView mv=new ModelAndView();
		mv.addObject("page", p);
		return mv;
		
	}
	
	@RequestMapping(path = "/edit", name="编辑人脸识别包")
	public ModelAndView edit(HttpServletRequest req, HttpServletResponse res){
		String idStr=req.getParameter("id");
		int id=0;
		if(idStr!=null&&Validator.isNum(idStr)){
			id=Integer.parseInt(idStr);
		}
		
		Map<String,Object> model=faceService.findById(id);
		ModelAndView mv=new ModelAndView();
		mv.addObject("obj", model);
		return mv;
	}
	
	@RequestMapping(path = "/save", name="保存人脸识别包")
	public Result save(HttpServletRequest req, HttpServletResponse res){
		String idStr=req.getParameter("id");
		int id=0;
		if(idStr!=null&&Validator.isNum(idStr)){
			id=Integer.parseInt(idStr);
		}
		String url=req.getParameter("url");
		String description=req.getParameter("description");
		
		int rs = faceService.save(id, url, description);
		
		if(rs>0){
			setFaceUrl();
			return error(1,"保存成功！");
		}else{
			return error(0,"保存失败！");
		}
	}
	
	@RequestMapping(path = "/del", name="删除包")
	public Result del(HttpServletRequest req, HttpServletResponse res){
		String idStr=req.getParameter("id");
		int id=0;
		if(idStr!=null&&Validator.isNum(idStr)){
			id=Integer.parseInt(idStr);
		}
		int rs = faceService.del(id);
		if(rs>0){
			setFaceUrl();
			return error(1,"操作成功！");
		}else{
			return error(0,"操作失败！");
		}
	}
	
	private void setFaceUrl(){
		//更新最新人脸识别包地址信息到redis
		String url = faceService.findNewUrl();
		redisService.set("face_package_url", url);
	}
}
